package com.jdls.tanhua.dubbo.impl;

import com.jdls.tanhua.dubbo.MovementApi;
import com.jdls.tanhua.dubbo.utils.IdWorker;
import com.jdls.tanhua.mongo.Friend;
import com.jdls.tanhua.mongo.Movement;
import com.jdls.tanhua.mongo.MovementTimeLine;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;

import java.util.List;

/**
 * @author 嘉德罗斯
 * @date 2021/10/27
 */
@DubboService
public class MovementImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Override
    //@Async
    public Movement save(Movement movement) {
        movement.setPid(idWorker.getNextId("movement"));
        movement.setCreated(System.currentTimeMillis());
        mongoTemplate.save(movement);
        Query query = Query.query(Criteria.where("pid").is(movement.getPid()));
        movement = mongoTemplate.findOne(query, Movement.class);
        return movement;
    }

    @Override
    public List<Friend> findOne(Movement movement) {
        Criteria criteria = Criteria.where("userId").is(movement.getUserId());
        Query q = Query.query(criteria);
        List<Friend> friends = mongoTemplate.find(q, Friend.class);

        return friends;
    }

    @Override
    public Movement findOne(ObjectId id) {
        Query query = Query.query(Criteria.where("id").is(id));
        Movement movement = mongoTemplate.findOne(query, Movement.class);
        return movement;
    }

    @Override
    public List<Movement> findAll(Long userId,Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        List<Movement> movements = mongoTemplate.find(query, Movement.class);

        return movements;
    }

    @Override
    public List<Movement> findAll(List<ObjectId> movementIds, Integer page, Integer pagesize) {

        Query query = Query.query(Criteria.where("id").in(movementIds))
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page-1)*pagesize)
                .limit(pagesize);
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return movements;

    }

    @Override
    public List<Movement> findMovement(List<Long> ids, Integer page, Integer pagesize) {

        Query query = Query.query(Criteria.where("userId").in(ids))
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page-1)*pagesize)
                .limit(pagesize);
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return movements;

    }
}
